package io.gitee.yanbinchen;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

import java.util.List;

/**
 * @author: alex
 * @since : 2025-02-28 18:20
 */
public class ProtostuffUtils {
    public static <T> byte[] serializer(T obj) {
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema schema = RuntimeSchema.getSchema(obj.getClass());
            return ProtobufIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new SuperCacheException(-1,"Serialization failed");
        } finally {
            buffer.clear();
        }
    }

    public static <T> T deserializer(byte[] data, Class<T> clz) {
        Schema<T> schema = RuntimeSchema.getSchema(clz);
        T obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, obj, schema);
        return obj;
    }

    public static <T> byte[] serializeList(List<T> objList, Class<T> clazz) {
        CacheWrapper<T> wrapper = new CacheWrapper<>(objList);
        RuntimeSchema<CacheWrapper<T>> schema = RuntimeSchema.createFrom((Class<CacheWrapper<T>>) wrapper.getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            return ProtostuffIOUtil.toByteArray(wrapper, schema, buffer);
        } catch (Exception e) {
            throw new SuperCacheException(-1,"Serialization failed");
        }  finally {
            buffer.clear();
        }
    }

    public static <T> List<T> deserializeList(byte[] data, Class<T> clazz) {
        RuntimeSchema<CacheWrapper<T>> schema = RuntimeSchema.createFrom((Class<CacheWrapper<T>>) new CacheWrapper<T>().getClass());
        CacheWrapper<T> wrapper = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, wrapper, schema);
        return wrapper.getData();
    }
}
